<template>
  <view class="blacklist-page">
    <Navbar title="黑白名单管理" />

    <!-- 黑白名单设备管理 -->
    <view class="table-section">
      <view class="table-header">
        <view class="header-cell">电器管理</view>
        <view class="header-cell status-cell">状态</view>
        <view class="header-cell add-cell" @click="addDevice">
          <image src="/static/img/minePages/add-btn.png" mode="widthFix" class="add-btn"></image>
          <text class="add-btn-text">添加</text>
        </view>
      </view>
      <view class="table-list">
        <view class="table-row" v-for="(item, idx) in deviceList" :key="item.id">
          <view class="row-cell">{{ item.name }}</view>
          <view class="row-cell">
            <tn-switch 
              v-model="item.enabled"
              active-color="#268EDA"
              inactive-color="rgba(255, 255, 255, 0.2)"
              size="sm"
              :before-change="(newValue) => beforeDeviceChange(item)"
            />
          </view>
          <view class="row-cell">
            <text class="manage-btn" @click="manageDevice(item)">管理</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 功率阈值管理 -->
    <view class="table-section">
      <view class="table-header">
        <view class="header-cell">域值管理 (w)</view>
        <view class="header-cell status-cell">状态</view>
        <view class="header-cell add-cell" @click="addThreshold">
          <image src="/static/img/minePages/add-btn.png" mode="widthFix" class="add-btn"></image>
          <text class="add-btn-text">添加</text>
        </view>
      </view>
      <view class="table-list">
        <view class="table-row" v-for="(item, idx) in thresholdList" :key="item.id">
          <view class="row-cell">{{ item.minValue }}-{{ item.maxValue }}</view>
          <view class="row-cell">
            <tn-switch 
              v-model="item.enabled"
              active-color="#268EDA"
              inactive-color="rgba(255, 255, 255, 0.2)"
              size="sm"
              :before-change="(newValue) => beforeThresholdChange(item, idx)"
            />
          </view>
          <view class="row-cell">
            <text class="manage-btn" @click="manageThreshold(item)">管理</text>
          </view>
        </view>
      </view>
    </view>
  </view>
  
  <!-- 电器选择器 -->
  <tn-picker
    v-model:open="showDevicePicker"
    :data="deviceOptions"
    :immediate-change="false"
    :mask="true"
    :show-cancel="false"
    confirm-color="#268EDA"
    label-key="label"
    value-key="value"
    @confirm="onDeviceConfirm"
  />
</template>

<script setup>
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import Navbar from '@/components/Navbar.vue';
import { mygo } from '@/utils/useNavigator';
import { createRequest } from '@/utils/request';

// 本地状态管理
const deviceList = ref([]);
const thresholdList = ref([]);
const deviceOptions = ref([]);

// 电器选择相关
const showDevicePicker = ref(false);

const manageDevice = (item) => {
  mygo('/pages/minePages/blackEdit', { id: item.id });
}

const addDevice = () => {
  showDevicePicker.value = true;
}

const onDeviceConfirm = async (value, pickerItem) => { 
  
  // 根据设备ID获取设备名称
  const selectedDevice = deviceOptions.value.find(option => option.value === value);
  if (!selectedDevice) {
    uni.showToast({ title: '设备信息不存在', icon: 'none' });
    return;
  }
  
  const deviceName = selectedDevice.label;
  
  // 检查是否已存在
  const exists = deviceList.value.some(device => device.name === deviceName);
  if (exists) {
    uni.showToast({ title: '该电器已存在', icon: 'none' });
    return;
  }
  
  try {
    // 调用统一接口添加电器规则
    const response = await createRequest('/blackList/addBlackListRule', {
      method: 'POST',
      data: {
        ruleName: `电器规则_${Date.now()}`,
        ruleType: 1, // 电器规则
        deviceId: value,
        deviceName: deviceName
      }
    });

    if (response.code === 200) {
      // 获取返回的ruleId
      const ruleId = response.data;
      
      // 跳转到电器编辑页面，传递ruleId
      mygo('/pages/minePages/blackEdit', { id: ruleId });
      
      showDevicePicker.value = false;
    }
  } catch (error) {
    uni.showToast({ title: '添加失败，请重试', icon: 'none' });
  }
}

const manageThreshold = (item) => {
  mygo('/pages/minePages/thresholdEdit', { 
    id: item.id,
    minValue: item.minValue,
    maxValue: item.maxValue
  });
}

const addThreshold = async () => {
  // 检查是否已存在相同的阈值范围
  const exists = thresholdList.value.some(threshold => 
    threshold.minValue === 0 && threshold.maxValue === 1
  );
  
  if (exists) {
    uni.showToast({ title: '有待编辑的阈值', icon: 'none' });
    return;
  }
  
  try {
    // 调用统一接口添加阈值规则
    const response = await createRequest('/blackList/addBlackListRule', {
      method: 'POST',
      data: {
        ruleName: `阈值规则_${Date.now()}`,
        ruleType: 2, // 阈值规则
        powerMin: 0,
        powerMax: 1
      }
    });

    if (response.code === 200) {
      // 获取返回的ruleId
      const ruleId = response.data;
      
      // 跳转到阈值编辑页面，传递ruleId和默认阈值参数
      mygo('/pages/minePages/thresholdEdit', { 
        id: ruleId,
        minValue: 0,
        maxValue: 1
      });
    }
  } catch (error) {
    uni.showToast({ title: '添加失败，请重试', icon: 'none' });
  }
}

// 电器开关切换处理
const beforeDeviceChange = async (device) => {
  try {
    // 发起请求修改状态
    const response = await createRequest(`/blackList/changeRuleStatus/${device.id}`, {
      method: 'POST'
    });

    // 检查响应状态
    if (response.code === 200) {
      // 请求成功，允许切换（组件会自动切换状态）
      return true;
    } else {
      return false; // 阻止切换
    }
  } catch (error) {
    return false; // 阻止切换
  }
};

// 阈值开关切换处理
const beforeThresholdChange = async (threshold, index) => {
  try {
    // 发起请求修改状态
    const response = await createRequest(`/blackList/changeRuleStatus/${threshold.id}`, {
      method: 'POST'
    });

    // 检查响应状态
    if (response.code === 200) {
      // 请求成功，允许切换（组件会自动切换状态）
      return true;
    } else {
      return false; // 阻止切换
    }
  } catch (error) {
    return false; // 阻止切换
  }
};

// 获取黑白名单规则数据
const fetchBlacklistRulesData = async () => {
  try {
    const response = await createRequest('/blackList/getBlackListRules');

    if (response.code === 200 && response.data) {
      // 映射电器规则数据
      if (response.data.applianceRules) {
        const mappedDevices = response.data.applianceRules.map(item => ({
          id: item.id,
          name: item.deviceName,
          enabled: item.status === 1 // 0=false, 1=true
        }));
        
        deviceList.value = mappedDevices;
      }

      // 映射阈值规则数据
      if (response.data.thresholdRules) {
        const mappedThresholds = response.data.thresholdRules.map(item => ({
          id: item.id,
          enabled: item.status === 1, // 0=false, 1=true
          minValue: item.powerMin,
          maxValue: item.powerMax
        }));
        
        thresholdList.value = mappedThresholds;
      }
    }
  } catch (error) {
    console.error('获取黑白名单规则数据失败:', error);
  }
};

// 获取电器选项数据
const fetchDeviceOptionsData = async () => {
  try {
    const response = await createRequest('/devices');

    if (response.code === 200 && response.data) {
      deviceOptions.value = response.data.map(device => ({
        label: device.deviceName,
        value: device.id
      }));
    }
  } catch (error) {
    console.error('获取电器选项数据失败:', error);
  }
};

onLoad(async () => {
  await Promise.all([
    fetchBlacklistRulesData(),
    fetchDeviceOptionsData(),
  ]);
});
</script>

<style scoped lang="scss">
.blacklist-page {
  @include page-with-header;
  background: #172869;
  min-height: 100vh;
  padding-bottom: 40rpx;
}

.table-section {
  border-radius: 10rpx;
  margin: 40rpx 24rpx 0 24rpx;
  overflow: hidden;
}

.table-header {
  display: flex;
  align-items: center;
  background: rgba(255,255,255,0.08);
  padding: 0 24rpx;
  height: 80rpx;
}

.header-cell {
  flex: 1;
  color: rgba(255,255,255,0.8);
  font-size: 32rpx;
  font-weight: 500;
  text-align: left;
  display: flex;
  align-items: center;
  height: 80rpx;
}

.status-cell {
  padding-left: 50rpx;
  box-sizing: border-box;
}

.add-cell {
  flex: 0 0 120rpx;
  text-align: right;
  cursor: pointer;
  justify-content: flex-end;
}

.add-btn {
  width: 28rpx;
  margin-right: 10rpx;
}

.add-btn-text {
  font-size: 28rpx;
  color: #04F7F4;
}

.table-list {
  width: 100%;
}

.table-row {
  display: flex;
  align-items: center;
  border-bottom: 1rpx solid rgba(255,255,255,0.08);
  height: 80rpx;
  padding: 0 24rpx;
}

.table-row:last-child {
  border-bottom: none;
}

.row-cell {
  flex: 1;
  color: rgba(255,255,255,0.8);
  font-size: 28rpx;
  display: flex;
  align-items: center;
  height: 80rpx;
  justify-content: flex-start;
}

.row-cell:nth-child(2) {
  justify-content: center;
}

.row-cell:last-child {
  justify-content: flex-end;
}

.manage-btn {
  color: #ff8c3a;
  font-size: 28rpx;
  font-weight: 500;
  cursor: pointer;
}

/* Picker组件样式优化 */
:deep(.uni-picker-view-mask) {
  background: transparent !important;
}

:deep(.tn-picker__content) {
  background: #172869 !important;
  border-radius: 20rpx 20rpx 0 0 !important;
}

:deep(.tn-picker__header) {
  background: #172869 !important;
  border-bottom: 1rpx solid rgba(255, 255, 255, 0.1) !important;
}

:deep(.tn-picker__confirm) {
  color: #1ec8e1 !important;
}

:deep(.tn-picker__cancel) {
  color: rgba(255, 255, 255, 0.6) !important;
}

:deep(.tn-picker__title) {
  color: #fff !important;
}

:deep(.tn-picker-view__item) {
  color: #fff !important;
}

:deep(.tn-picker-view__item--selected) {
  color: #1ec8e1 !important;
}
</style>